<?php
$SendMail = new SendMail();
$SendMail->send();
/**
 * 发送垃圾邮件的类
 */
class SendMail{
	/**
	 * 配置
	 */
	private $config;
	/**
	 * 发送邮件对象
	 */
	private $PHPMailer;//mail类
	/**
	 * 发送邮件的内容
	 */
	private $body;
	/**
	 * 构造函数初始化配置，获取发送内容，初始化email对象
	 */
	public function __construct(){
		$this->config	= parse_ini_file('mail.ini',true);
		$this->body		= file_get_contents('email.html');
		$this->initEmail();
	}
	/**
	 * 根据列表发送邮件
	 * 按照每组10封发送 一共1000组
	 */
	public function send(){
		ob_start();
		$list = $this->getEmaiList();
		$this->PHPMailer->Body = $this->body;
		$i=0;$count=count($list);
		foreach($list as $v){
			if(++$i%10 == 0){//按照每组10封发送
				$this->PHPMailer->Send();
				$this->PHPMailer->ClearAddresses();
			}else{
				$this->PHPMailer->AddAddress($v, "");
			}
		}
		$this->PHPMailer->Send();//发送剩余的邮件
		$Log=ob_get_contents();
		ob_end_clean();
		if($Log)$this->log($Log);
		
		$this->setConfig();
	}
	/**
	 * 发送邮件
	 */
	private  function getEmaiList(){
		$file_name = 'mail_list/'.$this->config['send']['file_id'];
		$list = explode("\n",file_get_contents($file_name));
		foreach($list AS $k =>$v){
			if(!preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',$v)){
				unset($list[$k]);
			}
		}
		return $list;
	}
	/**
	 * 重置配置文件
	 */
	private function setConfig(){
		$str = '';
		foreach($this->config as $k=>$v){
			$str .= "[$k]\n";
			foreach($v as $k1=>$v1){
				if($k1=='file_id')$v1++;
				$str.="{$k1}={$v1}\n";
			}
		}
		unlink('mail.ini');
		file_put_contents('mail.ini',$str);
	}
	/**
	 * 重置配置文件
	 */
	private function initEmail(){
		require('PHPMailer/PHPMailer.class.php');		
		$this->PHPMailer = new PHPMailer(); 
		$this->PHPMailer->IsSMTP();               
		$this->PHPMailer->Host			= $this->config['email']['host'];
		$this->PHPMailer->Port			= $this->config['email']['port'];
		$this->PHPMailer->SMTPAuth		= true;
		$this->PHPMailer->Username		= $this->config['email']['username'];
		$this->PHPMailer->Password		= $this->config['email']['password'];
		$this->PHPMailer->From			= $this->config['email']['username'];		
		$this->PHPMailer->FromName		= $this->config['email']['fromname'];
		$this->PHPMailer->Subject		= $this->config['email']['subject'];
		$this->PHPMailer->ContentType	= "text/html";
		$this->PHPMailer->CharSet		= "UTF-8";  
		$this->PHPMailer->Encoding		= "base64";
		$this->PHPMailer->IsHTML(true);  
	}
	private function log($log){
		$FileName='Log/Log_'.date('Y-m-d').'.log';
		if ($handle = fopen($FileName,'a+')) {
			fwrite($handle,date('Y-m-d H:i:s').':  '.$log."\n");
			fclose($handle);
		}
	}
}
?>
